package com.netty.demo.nio.handler.impl;

import com.netty.demo.protocol.packet.LoginRequestPacket;
import com.netty.demo.protocol.packet.LoginResponsePacket;
import com.netty.demo.utils.ConsoleUtils;
import com.netty.demo.utils.LoginUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Date;

public class LoginResponseHandler extends SimpleChannelInboundHandler<LoginResponsePacket> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginResponsePacket loginResponsePacket) throws Exception{
        if (!loginResponsePacket.isSuccess()) {
            System.out.println(new Date() + ": 客户端登录失败，原因：" + loginResponsePacket.getReason());
        } else {
            System.out.println(new Date() + ": 客户端登录成功");
            LoginUtils.markLogin(ctx, loginResponsePacket.getUserId());
            ConsoleUtils.startClientConsoleThread(ctx.channel());
        }
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        // 创建登录对象
        LoginRequestPacket loginRequestPacket = new LoginRequestPacket();
        loginRequestPacket.setUserId(LoginUtils.createUserId());
        loginRequestPacket.setUsername("zhangqiang");
        loginRequestPacket.setPassword("pwd");

        // 写数据
        ctx.channel().writeAndFlush(loginRequestPacket);
    }

}
